package com.upc.sealback.utils;

import com.aliyun.oss.model.*;
import com.upc.sealback.config.ResponseResult;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random;

import static com.upc.sealback.utils.FontUtils.SEAL_SAVE_PATH;

/**
 * 对象存储工具类
 */
public class FileOSS {
    public static final String END_POINT = "";
    public static final String ACCESS_KEY_ID = "";
    public static final String ACCESS_KEY_SECRET = "";
    public static final String BUCKET_NAME = "";

    /**
     * 上传字节流数组
     * @param input 字节数组
     * @return
     * @throws Exception
     */
    public static ResponseResult<Object> streamUploadOSS(InputStream input) throws Exception {
        /*String endpoint = "https://oss-cn-qingdao.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tChvEP9WosfbJPegVJ1";
        String accessKeySecret = "PgD5cRcdG7PfmwpwogLedAY3I3xmej";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "sealzy";*/
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        Random random = new Random();
        String fileName = System.currentTimeMillis() + random.nextInt(1000) + ".png";

        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        //String filePath= "/Users/zymac/Desktop/SealBack/src/main/resources/static/upload/upload/"+fileName;
        String fileUrl = null;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, input);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
                /*System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());*/
            return ResponseResult.getErrorResult(oe.getErrorCode(), oe.getMessage());
        } catch (ClientException ce) {
                /*System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());*/
            return ResponseResult.getErrorResult(ce.getErrorCode(), ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                fileUrl = "https://sealzy.oss-cn-qingdao.aliyuncs.com/" + fileName;
            }
        }
        return ResponseResult.getSuccessResult(fileUrl);
    }

    public static ResponseResult<Object> streamPdfUploadOSS(InputStream input) throws Exception {
        /*String endpoint = "https://oss-cn-qingdao.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tChvEP9WosfbJPegVJ1";
        String accessKeySecret = "PgD5cRcdG7PfmwpwogLedAY3I3xmej";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "sealzy";*/
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        Random random = new Random();
        String fileName = System.currentTimeMillis() + random.nextInt(1000) + ".pdf";

        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        //String filePath= "/Users/zymac/Desktop/SealBack/src/main/resources/static/upload/upload/"+fileName;
        String fileUrl = null;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, input);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
                /*System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());*/
            return ResponseResult.getErrorResult(oe.getErrorCode(), oe.getMessage());
        } catch (ClientException ce) {
                /*System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());*/
            return ResponseResult.getErrorResult(ce.getErrorCode(), ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                fileUrl = "https://sealzy.oss-cn-qingdao.aliyuncs.com/" + fileName;
            }
        }
        return ResponseResult.getSuccessResult(fileUrl);
    }

    /**
     * 上传本地文件
     * @param fileName 本地文件名
     * @return
     * @throws Exception
     */
    public static ResponseResult<Object> fileUploadOSS(String fileName) throws Exception {
        Random random = new Random();
        String objectName = System.currentTimeMillis() + random.nextInt(1000) + fileName;
        String filePath = SEAL_SAVE_PATH + fileName;
        String fileUrl = null;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, new File(filePath));

            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            return ResponseResult.getErrorResult(oe.getErrorCode(), oe.getMessage());
        } catch (ClientException ce) {
            return ResponseResult.getErrorResult(ce.getErrorCode(), ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                fileUrl = "https://sealzy.oss-cn-qingdao.aliyuncs.com/" + objectName;

            }
        }
        return ResponseResult.getSuccessResult(fileUrl);
    }


    /**
     * 下载指定文件到本地
     * @param fileName 文件名
     * @return 文件路径或者错误提示
     * @throws Exception
     */
    public static ResponseResult<Object> fileGetOss(String fileName) throws Exception {
        String filePath = SEAL_SAVE_PATH + fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(BUCKET_NAME, fileName), new File(filePath));
        } catch (OSSException oe) {
            return ResponseResult.getErrorResult(oe.getErrorCode(),oe.getErrorMessage());
        } catch (ClientException ce) {
            return ResponseResult.getErrorResult("400", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ResponseResult.getSuccessResult(filePath);
    }



    /**
     * 批量删除OSS里的文件
     * @return
     * @throws Exception
     */
        public static ResponseResult<Object> delOSSFileArray(List<String> keys) throws Exception{
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            try {
                // 删除文件。
                // 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。
//                List<String> keys = new ArrayList<String>();
//                keys.add("1648561304927.png");
//                keys.add("1648561390313.png");
//                keys.add("1648561480056.png");

                DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(BUCKET_NAME).withKeys(keys).withEncodingType("url"));
                List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
                try {
                    for(String obj : deletedObjects) {
                        String deleteObj =  URLDecoder.decode(obj, "UTF-8");
                       // System.out.println(deleteObj);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } catch (OSSException oe) {
                /*System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());*/
                return ResponseResult.getErrorResult(oe.getErrorCode(),oe.getErrorMessage());
            } catch (ClientException ce) {
                /*System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());*/
                return ResponseResult.getErrorResult(ce.getErrorCode(),ce.getErrorMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            return ResponseResult.getSuccessResult("success");
    }


}
